package utils

import (
	"fmt"
	"hash/adler32"
	"math"
	"strings"
	"unicode"
)

func BuildSuffixSvg(suffix string, background string) string {
	suffix = strings.Map(func(r rune) rune { return unicode.ToUpper(r) }, suffix)
	if len(suffix) > 4 {
		suffix = suffix[0:4]
	}
	total := adler32.Checksum([]byte(suffix))
	hue := total % 360
	r, g, b := hsv2rgb(float64(hue)/360, 0.3, 0.9)
	if background == "" {
		background = fmt.Sprintf("rgb(%d,%d,%d)", r, g, b)
	}
	return `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:` + background + `;" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">` + suffix + `</tspan></text></g>
        </svg>`
}

func hsv2rgb(h, s, v float64) (uint8, uint8, uint8) {
	i := math.Floor(h * 6)
	f := h*6 - i
	p := v * (1 - s)
	q := v * (1 - f*s)
	t := v * (1 - (1-f)*s)

	var r, g, b float64
	switch int(i) % 6 {
	case 0:
		r, g, b = v, t, p
	case 1:
		r, g, b = q, v, p
	case 2:
		r, g, b = p, v, t
	case 3:
		r, g, b = p, q, v
	case 4:
		r, g, b = t, p, v
	case 5:
		r, g, b = v, p, q
	}

	return uint8(math.Floor(r*255 + 0.5)), uint8(math.Floor(g*255 + 0.5)), uint8(math.Floor(b*255 + 0.5))
}
